using System;
using CommonDomain.Persistence;

namespace Sponsorship.Domain.Sponsorships
{
    /// <summary>
    /// Handles domain commands dealing with <see cref="Sponsorship"/> instances.
    /// </summary>
    public class SponsorshipCommandHandler :
        ICommandHandler<EnterSponsorship>,
        ICommandHandler<ChangeSponsorship>,
        ICommandHandler<DeleteSponsorship>
    {
        private readonly IRepository _repository;

        public SponsorshipCommandHandler (IRepository repository)
        {
            _repository = repository;
        }

        public void Handle (EnterSponsorship command)
        {
            var sponsorship = new Sponsorship (command.SponsorshipId, command.SponsorshipTypeId, command.PersonId, command.SponsorId, command.Amount, command.StartDate, command.EndDate, command.Period, command.Comment);
            SaveSponsorship (sponsorship);
        }

        public void Handle (ChangeSponsorship command)
        {
            Sponsorship sponsorship = LoadSponsorship (command.SponsorId, command.Version);

            //execute domain logic and get back a new aggregate
            sponsorship.Delete();

            //save new raised events of aggregate into eventstore
            SaveSponsorship (sponsorship);
        }

        public void Handle (DeleteSponsorship command)
        {
            Sponsorship sponsorship = LoadSponsorship (command.SponsorshipId, command.Version);

            //execute domain logic and get back a new aggregate
            sponsorship.Delete();

            //save new raised events of aggregate into eventstore
            SaveSponsorship (sponsorship);
        }

        private Sponsorship LoadSponsorship (Guid guid)
        {
            return _repository.GetById<Sponsorship> (guid);
        }

        private Sponsorship LoadSponsorship (Guid guid, int version)
        {
            return _repository.GetById<Sponsorship> (guid, version);
        }

        private void SaveSponsorship (Sponsorship sponsorship)
        {
            _repository.Save (sponsorship, Guid.NewGuid()); // Every commit has a new ID
        }
    }
}